package com.sise.aio和bio和nio.bio.bio3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 基于线程池进行改善的一个bio server
 *
 * @author idea
 * @data 2019/4/6
 */
public class Server implements Runnable {

    private ServerSocket serverSocket;

    private ExecutorService executorService=Executors.newFixedThreadPool(2);

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(9099);
            System.out.println("server is open!");
            Socket sc = serverSocket.accept();
            System.out.println("接受到链接了");
            executorService.submit(new Handler(sc));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Thread thread=new Thread(new Server());
        thread.start();
    }


}

class Handler implements Runnable {

    private Socket socket;

    public Handler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader buf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String content = buf.readLine();
            System.out.println("----");
            while (content != null) {
                System.out.println("获取到信息！");
                content = buf.readLine();
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}